package com.mall.xiaomi.service.impl;

import com.mall.xiaomi.exception.ExceptionEnum;
import com.mall.xiaomi.exception.XmException;
import com.mall.xiaomi.mapper.CollectMapper;
import com.mall.xiaomi.pojo.Collect;
import com.mall.xiaomi.pojo.Product;
import com.mall.xiaomi.service.CollectService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author zhanggaoxiang
 * @ClassName CollectServiceImpl
 * @Description TODO
 * @Date 2021/2/25 14:44
 * @Version 1.0
 **/
@Service
public class CollectServiceImpl implements CollectService {
    @Autowired
    private CollectMapper collectMapper;

    @Override
    public List<Product> getCollectByUid(Integer userId) {
        List<Product> list;
        try {
            list = collectMapper.getCollectByUid(userId);
            if (ArrayUtils.isEmpty(list.toArray())) {
                throw new XmException(ExceptionEnum.GET_COLLECT_NOT_FOUND);
            }
        } catch (XmException e) {
            e.printStackTrace();
            throw new XmException(ExceptionEnum.GET_COLLECT_ERROR);
        }
        return list;
    }

    @Override
    public void delCollectById(Integer productId, Integer userId) {
        Collect collect=new Collect();
        collect.setProductId(productId);
        collect.setUserId(userId);
        try {
            int count=collectMapper.delCollectById(collect);
            if (count!=1){
                throw new XmException(ExceptionEnum.DELETE_COLLECT_ERROR);
            }
        }catch (XmException e){
            e.printStackTrace();
            throw new XmException(ExceptionEnum.DELETE_COLLECT_ERROR);
        }
    }

    @Override
    @Transactional
    public void addCollect(Integer productId, Integer userId) {
        Collect collect=new Collect();
        collect.setProductId(productId);
        collect.setUserId(userId);
        Collect collect1=collectMapper.findCollectById(collect);
        if (collect1!=null){
            throw new XmException(ExceptionEnum.SAVE_COLLECT_REUSE);
        }
        collect.setCollectTime(new Date().getTime());
        int count=collectMapper.addCollect(collect);
        if (count!=1){
            throw new XmException(ExceptionEnum.SAVE_COLLECT_ERROR);
        }

    }
}
